package study.仪器解析.串口化通信.生化仪.监听COM1;

import jssc.SerialPort;
import jssc.SerialPortException;

/**
 * @Author 刘伟涛
 * @Date 2024/8/7 14:06
 **/
public class SerialCommunicationHandler {
    private SerialPort serialPort;

    public SerialCommunicationHandler(String portName) {
        serialPort = new SerialPort(portName);
    }

    public void initializePort() throws SerialPortException {
        serialPort.openPort();
        serialPort.setParams(
                SerialPort.BAUDRATE_9600,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE
        );
    }

    public void closePort() throws SerialPortException {
        if (serialPort.isOpened()) {
            serialPort.closePort();
        }
    }

    public String sendData(String data) throws SerialPortException {
        serialPort.writeString(data);
        return serialPort.readString(); // 读取设备的响应
    }
}
